package apis

import (
	"github.com/gin-gonic/gin"
	"zorm-learn/app/auth/service"
	"zorm-learn/app/util"
)

var Routers = make([]func(*gin.RouterGroup), 0)

func init() {
	Routers = append(Routers, func(group *gin.RouterGroup) {
		routerGroup := group.Group("/auth")
		routerGroup.POST("/login", login)
	})
}

func login(context *gin.Context) {
	ctx, _ := util.MainCtx.DM.BindContextDBConnection(context)
	auth := context.PostForm("auth")
	encrypt := util.Md5Encrypt(auth)

	user, err := service.FindByPassword(ctx, encrypt)
	if err != nil {
		context.JSON(200, util.Fail(err.Error()))
		return
	}
	if user != nil {
		session := util.MainCtx.Sessions
		token := session.CreateSession(user)
		context.JSON(200, util.Success(token))
		return
	}
	context.JSON(200, util.Fail("user not found !"))
}
